package com.itany.corejava.code16_反射;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月18日 14:42
 */
public class Test04_Field {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class c = User.class;

        //1.获取当前类以及其父类中所有public修饰的属性
        Field[] fields = c.getFields();
        System.out.println(Arrays.toString(fields));

        // 2.获取当前类的所有属性，不区分修饰符
        Field[] fields2 = c.getDeclaredFields();
        System.out.println(Arrays.toString(fields2));

        // 3.获取当前类以及其父类中指定的由public修饰的属性
        Field usernameField = c.getField("username");
        System.out.println(usernameField);

        //如果是private修饰，则报错
        // Field passwordField=c.getField("password");
        // System.out.println(passwordField);

        //父类的
        Field ageField=c.getField("age");
        System.out.println(ageField);

        Field passwordField=c.getDeclaredField("password");
        System.out.println(passwordField);

        //无法获取父类的属性，报错
        // Field age2Field=c.getDeclaredField("age");
        // System.out.println(age2Field);

        User user=new User();
        // set(Object obj,Object value)
        // obj指的是要给哪个对象设置
        // value值是多少
        usernameField.set(user,"alice");
        usernameField.set(user,"coco");

        //不能访问private修饰的属性
        // passwordField.set(user,"123456");


        // setAccessible(true)破坏封装原则
        passwordField.setAccessible(true);
        passwordField.set(user,"123456");
        System.out.println(user);

        String username= (String) usernameField.get(user);
        String password= (String) passwordField.get(user);
        System.out.println(username);
        System.out.println(password);



    }
}
